| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
- import { FileService } from '@/server/modules/files/file.service';
- import { MinioService } from '@/server/modules/files/minio.service';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { AppDataSource } from '@/server/data-source';
- import { AuthContext } from '@/server/types/context';
- import { authMiddleware } from '@/server/middleware/auth.middleware';
- // 获取文件URL路由
- const getFileUrlRoute = createRoute({
- method: 'get',
- path: '/url',
- middleware: [authMiddleware],
- request: {
- params: z.object({
- id: z.coerce.number().openapi({
- param: { name: 'id', in: 'path' },
- example: 1,
- description: '文件ID'
- })
- })
- },
- responses: {
- 200: {
- description: '获取文件URL成功',
- content: {
- 'application/json': {
- schema: z.object({
- url: z.string().url().openapi({
- description: '文件访问URL',
- example: 'https://minio.example.com/bucket/file-key'
- })
- })
- }
- }
- },
- 404: {
- description: '文件不存在',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 500: {
- description: '服务器错误',
- content: { 'application/json': { schema: ErrorSchema } }
- }
- }
- });
- // 创建文件服务实例
- const fileService = new FileService(AppDataSource);
- // 创建路由实例
- const app = new OpenAPIHono<AuthContext>().openapi(getFileUrlRoute, async (c) => {
- try {
- const { id } = c.req.valid('param');
- const url = await fileService.getFileUrl(id);
- return c.json({ url }, 200);
- } catch (error) {
- const message = error instanceof Error ? error.message : '获取文件URL失败';
- const code = (error instanceof Error && error.message === '文件不存在') ? 404 : 500;
- return c.json({ code, message }, code);
- }
- });
- export default app;
|